package app.base.common;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;


public class FileOperation {

	private String charsetEncoding = Utility.DEFAULT_CHARSET_ENCODING;

	private String fileName = null;

	public FileOperation(String fileName) throws Exception {
		this(fileName, null);
	}

	public FileOperation(String fileName, String charsetEncoding) throws Exception {
		if (fileName == null) {
			throw new Exception(
					"Class FileOperation ：the fileName param is null. ");
		}
		this.fileName = fileName.trim();

		if (charsetEncoding != null) {
			this.charsetEncoding = charsetEncoding.trim();
		}

	}

	public void writeto(String content, boolean append) throws Exception {
		writeto(content, null, append);
	}

	public void writeto(String content, String charsetEncoding, boolean append) throws Exception {
		if (content == null) {
			return;
		}

		String chstEncoding = this.charsetEncoding;

		if (charsetEncoding != null && charsetEncoding.trim().length() != 0) {
			chstEncoding = charsetEncoding.trim();
		}

		FileOutputStream fos = new FileOutputStream(this.fileName, append);

		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos,
				chstEncoding));

		try {

			bw.write(content);

		} catch (IOException e) {
			throw e;
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				bw.close();
			} catch (IOException e) {
				throw e;
			}
		}

	}

	public StringBuffer readfrom() throws Exception {
		return readfrom(null);
	}

	public StringBuffer readfrom(String charsetEncoding) throws Exception {
		String chstEncoding = this.charsetEncoding;

		if (charsetEncoding != null && charsetEncoding.trim().length() != 0) {
			chstEncoding = charsetEncoding.trim();
		}

		FileInputStream fis = new FileInputStream(this.fileName);

		BufferedReader br = new BufferedReader(new InputStreamReader(fis,
				chstEncoding));

		StringBuffer sb = new StringBuffer("");

		try {

			String line = null;

			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append(Utility.DOS_TERMINATORS);
			}

		} catch (IOException e) {
			throw e;
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				throw e;
			}
		}

		return sb;
	}

	public static void main(String[] args) throws Exception {

		FileOperation fo = new FileOperation(
				"E:\\codes\\java\\workspace\\oa\\bin\\SqlMapConfig.xml");

		// fo.writeto(content, "utf-8");

		System.out.println(fo.readfrom());
	}

}
